//引入three
import * as THREE from "three";
//引入控制器
import { OrbitControls } from "three/examples/jsm/Addons.js";

const sizes = {
  width: window.innerWidth,
  height: window.innerHeight,
};

//监听窗口变化事件
window.addEventListener("resize", () => {
  //   console.log(window.innerWidth);
  sizes.width = window.innerWidth;
  sizes.height = window.innerHeight;

  //调整相机
  camera.aspect = sizes.width / sizes.height;
  camera.updateProjectionMatrix(); //更新相机

  //调整渲染器
  renderer.setSize(sizes.width, sizes.height);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});

window.addEventListener("dblclick", () => {
  //   console.log("双击");
  if (!document.fullscreenElement) {
    //我们让画布进入全屏
    renderer.domElement.requestFullscreen();

    console.log("当前未全屏");
  } else {
    //从文档级别退出全屏
    document.exitFullscreen();
    console.log("当前已全屏");
  }
});

//场景
const scene = new THREE.Scene();

//物体
const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshBasicMaterial({ color: "#ffaaaa" })
);

scene.add(cube);

//相机
const camera = new THREE.PerspectiveCamera(
  55,
  sizes.width / sizes.height,
  0.1,
  400
);
camera.position.z = 3;
scene.add(camera);

//渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(sizes.width, sizes.height);
renderer.domElement.setAttribute("class", "my-canvas");
//调整像素比率解决模糊问题
// renderer.setPixelRatio(window.devicePixelRatio);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

document.body.appendChild(renderer.domElement);

//控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;

//加入轴辅助器
const aixsHelper = new THREE.AxesHelper(20);
scene.add(aixsHelper);

const change = () => {
  // 加了阻尼，所以要更新控制器
  controls.update();

  renderer.render(scene, camera);

  window.requestAnimationFrame(change);
};
change();
